#include <Ogre.h>
#include <OIS/OIS.h>
using namespace Ogre;

#include "MarbleMax.h"

bool Marble_Max::rollState(const FrameEvent& evt)
{
	//mDebugString.clear();					// clear the debug string

	if (evt.timeSinceLastFrame == 0)		// If this is the first frame, pick a speed
	{
		mMoveScale = .1;
		mRotScale = 0.1;
	}
	else									// Otherwise scale movement units by time passed since last frame
	{
											// Move about 100 units per second,
		mMoveScale = (mMoveSpeed * evt.timeSinceLastFrame);
											// Take about 10 seconds for full rotation
		mRotScale = mRotSpeed * evt.timeSinceLastFrame;
	}
	mMouse->capture();						// capture the mouse's current state
	mKeyboard->capture();					// capture the keyboard's current state

	mTranslateVector = mMoveVector.normalisedCopy() * mMoveScale;		// set the translation vector to be 100 units long and in the right direction
	moveCamera();							// move the camera
	if(mLeftMDown)
		createBall();
	//mWorld->get

	mRotX = 0;
	mRotY = 0;
	mLeftMUp = false;
	return true;
}

bool Marble_Max::startRoll()
{
	if(!buildTrack())
		return false;
	createBall();

	Object *obj = &Objects[0];

	return true;
}

bool Marble_Max::buildTrack()
{
	Ogre::StaticGeometry *sg = mSceneMgr->createStaticGeometry("MarbleTrack");
	if(Objects.size() == 0)
		return false;
	vector<Object>::iterator itr;
	for(itr = Objects.begin(); itr != Objects.end(); itr++)
	{
		if(!itr->isActive())
		{
			OgreNewt::CollisionPrimitives::TreeCollision *tc = new OgreNewt::CollisionPrimitives::TreeCollision(mWorld,itr->getNode(),true);
			OgreNewt::Body *bod = new OgreNewt::Body(mWorld,tc);
			bod->attachToNode(itr->getNode());
			bod->setPositionOrientation(itr->getLocation(),itr->getNode()->getOrientation());
			bod->setType(0);
			sg->addSceneNode(itr->getNode());
			mSceneMgr->destroySceneNode(itr->getNode());
		}
	}

	sg->build();
	return true;
}

bool Marble_Max::createBall()
{
	Object *obj = &Objects[0];
	Vector3 vec = obj->getLocation() + Vector3(0,50,0);
	tempNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("BallNode" + StringConverter::toString(numBalls),vec);
	tempEntity = mSceneMgr->createEntity("BallMesh" + StringConverter::toString(numBalls),SceneManager::PT_SPHERE);
	tempNode->setScale(.075,.075,.075);
	tempNode->attachObject(tempEntity);

	OgreNewt::CollisionPrimitives::Capsule *ball = new OgreNewt::CollisionPrimitives::Capsule(mWorld,2,2);
	OgreNewt::Body *bod = new OgreNewt::Body(mWorld,ball);
	bod->attachToNode(tempNode);
	bod->setMassMatrix(100,Vector3(0,-100,0));
	bod->setStandardForceCallback();
	bod->setPositionOrientation(vec,Quaternion::IDENTITY);
	bod->setVelocity(Vector3(0,-10,0));
	bod->setType(1);

	numBalls++;

	mLeftMDown = false;

	return true;
}